package com.solocredit.finance.ui.steps.fm

import android.annotation.SuppressLint
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.DensityUtils
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.databinding.FmMullaStepCommonBinding
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.ProFm
import com.solocredit.finance.ui.steps.act.MullaStepsAct
import com.solocredit.finance.ui.steps.adapter.MullaStepCommonAdapter
import com.solocredit.finance.utils.decoration.LinearSpacingItemDecoration
import com.solocredit.finance.utils.dialog.StepCommonPopup
import com.solocredit.finance.utils.event.MullaBehaviorTracker
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.weight.pickerview.builder.TimePickerBuilder
import com.solocredit.finance.weight.pickerview.listener.OnTimeSelectListener
import com.solocredit.finance.weight.pickerview.view.TimePickerView
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/30 14:19
 * @Annotation：认证流程 - 通用
 */
class MullaStepCommonFm(): ProFm() {
    private var _binding: FmMullaStepCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    private var stepTitle = ""

    private var commonAdapter: MullaStepCommonAdapter? = null
    private var mSelectPosition = -1

    //出生日期选择
    private var pvStartDateView: TimePickerView? = null

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaStepCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        rootViewBinding.containerLayout.setBackgroundColor("#00000000".toColorInt())
        if (stepItem != null){
            _binding?.textStepTitle?.text = stepItem?.optString("showTitle")
        }
        initMullaCommonViews()
        //不显示下一步按钮，放到外层StepAct显示下一步
        _binding?.btnNext?.visibility = View.GONE
    }

    override fun initMullaListener() {
        //下一步
        _binding?.btnNext?.setOnClickListener {
            onMullaSubmitCommonDataAction()
        }
    }

    override fun initMullaData() {
        _binding?.stepTipsLayout?.visibility = View.GONE
        val dataList = arrayListOf<JSONObject>()
        stepItem?.let {
            stepTitle = it.optString("stepTitle")
            HttpHelper.addMullaEventAction(String.format(MullaEventType.PAGE.MULLA_PAGE_STEP_COMMON_XX_START,stepTitle),"")

            if ("personal_info" == it.optString("stepTitle")){
                val showKey = getString(R.string.step_personal_info_tips_key)
                val showText = String.format(getString(R.string.step_personal_info_tips),showKey)
                val startIndex = showText.indexOf(showKey)
                val dataSecuritySpannable = SpannableString(showText)
                dataSecuritySpannable.setSpan(ForegroundColorSpan("#FF26005D".toColorInt()), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                //加粗
//                dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                _binding?.textStepTips?.text = dataSecuritySpannable
                _binding?.stepTipsLayout?.visibility = View.VISIBLE
            }

            val dataArray = it.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
        }
        commonAdapter?.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initMullaCommonViews(){
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerView?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(16f)
        _binding?.recyclerView?.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        commonAdapter = MullaStepCommonAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = commonAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        commonAdapter?.setOnItemChildClickListener { _, childView, position ->
            _binding?.root?.clearFocus()
            mSelectPosition = position
            val item = commonAdapter?.getItem(position)
            item?.let {
                when (it.optString("action")) {
                    "DATE_PICK" -> {//时间选择
                        showMullaBirthDialog()
                    }
                    "SELECT" -> {//选择
                        val dataList = arrayListOf<JSONObject>()
                        val dataArray = it.optJSONArray("values")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                dataList.add(dataArray.optJSONObject(i))
                            }
                        }
                        showSelectPopupwindow(childView, dataList)
                    }
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        _binding?.root?.let {
            val selectPopup = StepCommonPopup(requireContext())
            selectPopup.setWindowWidth(view.width + DensityUtils.dp2px(10f))
            selectPopup.setSelectItemListener(object : StepCommonPopup.IItemClickListener {
                //完成
                override fun onConfirmAction(data: JSONObject?) {
                    val item = commonAdapter?.getItem(mSelectPosition)
                    item?.put("selectItem",data)
                    commonAdapter?.notifyItemChanged(mSelectPosition)

                    if (data != null){
                        val subRemark = "${data.optString("value")}$$${data.optString("duration")}"
                        HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_SELECT,item?.optString("paramName")),subRemark)
                    }
                }
                //关闭监听
                override fun onDismissListener() {
                }
            })
            selectPopup.show(view, it)
            selectPopup.setBrandList(dataList)
        }
    }

    /**
     * 选择出生日期
     */
    var startTime = 0L
    private fun showMullaBirthDialog(){
        //开始选择时间
        startTime = System.currentTimeMillis()
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(context, object : OnTimeSelectListener {
                    override fun onTimeSelect(date: Date?, v: View?) {
                    }

                    @SuppressLint("SimpleDateFormat")
                    override fun onTimeSelectString(date: Date?, showDate: String?) {
                        val value = date?.let { SimpleDateFormat("yyyy-MM-dd").format(it) }
                        val obj = JSONObject()
                        obj.put("title", showDate)
                        obj.put("title_sw", showDate)
                        obj.put("value", value)

                        //可根据需要自行截取数据显示
                        val item = commonAdapter?.getItem(mSelectPosition)
                        item?.let {
                            it.put("selectItem", obj)
                            commonAdapter?.notifyItemChanged(mSelectPosition)

                            val subRemark = "${value}$$${System.currentTimeMillis() - startTime}"
                            HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_SELECT, it.optString("paramName")), subRemark)
                        }
                    }
                })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.dialog_mulla_birthday) { v ->
                    val ivClose = v.findViewById<ImageView>(R.id.ivClose)
                    ivClose.setOnClickListener {
                        pvStartDateView?.dismiss()
                    }
                    //确定
                    val btnDone = v.findViewById<TextView>(R.id.btnDone)
                    btnDone.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(16)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3f)
                .setTextXOffset(40, 40, 40, 40, 40, 40)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter("#FF08252C".toColorInt()) //设置选中项文字颜色
                .setTextColorOut("#FF9CA8AB".toColorInt())//默认颜色
                .setBgColor("#00000000".toColorInt())
                .isAlphaGradient(true)
                .setItemVisibleCount(5)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(requireContext(), R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            if (dialog != null){
                val dialogWindow = dialog.window
                if (dialogWindow != null) {
                    val params = dialogWindow.attributes
                    params.width = WindowManager.LayoutParams.MATCH_PARENT
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT
                    dialogWindow.attributes = params
                    dialogWindow.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.BOTTOM)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()
    }

    /**
     * 提交数据
     */
    private fun onMullaSubmitCommonDataAction(){
        _binding?.root?.clearFocus()
        HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_NEXT, stepTitle),"")
        if (!isAllowCommonSubmit()){
            showMullaErrorTipsDialog(getString(R.string.tips_submit_error), stepTitle)
            return
        }

        val params = JSONObject().addCommonParams().addRandomParams().apply {
//                put("path", stepItem.optString("apiUrl").replace("/",""))
        }
        commonAdapter?.let {
            for (i in 0..<it.itemCount){
                val item = it.getItem(i)
                if (item.has("selectItem")){
                    val selectItem = item.optJSONObject("selectItem")
                    if (selectItem != null){
                        params.put(item.optString("paramName"),selectItem.optString("value"))
                    }
                }
            }
        }

        // TODO: Step Next 批量埋点上报
        MullaBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)

        MullaLog.e(">>>>>>submit data >>>>>>>$params")
        stepItem?.let {
            val act = context as MullaStepsAct
            act.onMullaSubmitProcessAction(it.optString("apiUrl"),params)
        }
    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        commonAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                //存在 isMust && isMust == ”NO“  非必填
                if (item.has("isMust") && item.optString("isMust") == "NO"){
                    continue
                }
                //必填 && 没有内容 || 内容为空
                if (!item.has("selectItem")){
                    isAllow = false
                    break
                }
                val selectItem = item.optJSONObject("selectItem")
                if (selectItem == null){
                    isAllow = false
                    break
                }
                if (selectItem.optString("value").isEmpty()){
                    isAllow = false
                    break
                }
            }
        }
        return isAllow
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        if(event.eventType == MullaEventData.TYPE.MULLA_STEP_PHONEBOOK_SUBMIT){//提交信息
            onMullaSubmitCommonDataAction()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(String.format(MullaEventType.PAGE.MULLA_PAGE_STEP_COMMON_XX_END,stepTitle),"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}